<template>
  <div class="l-m-b">
    <div class="lmb-r">
      <ul class="lmb-r-tools" style="display: flex">
        <li>
          <a class="wl" id="btn-network" title="切换线路" @click="network"></a>
        </li>
        <li>
          <a class="qh" id="btn-switch" title="切换窗口" @click="switchPptToVideo"></a>
        </li>
        <!-- <li>
          <a class="only-audio" id="btn-audio" title="只听音频" @click="btnAudio"></a>
        </li> -->
        <li>
          <a class="clip-image" id="btn-clip" title="截图" @click="clipVideoImage"></a>
        </li>
        <li title="视频互动" name="interaction" t="video">
          <a class="video" data-title="视频互动"></a>
        </li>
        <li title="语音互动" name="interaction" t="audio">
          <a class="audio" data-title="语音互动"></a>
        </li>
        <li>
          <a class="gm" id="change-nickname" title="改名" @click="changeNickname"></a>
        </li>
        <div id="streamQuality"></div>
        <li style="width: 100px; margin-left: 140px">
          <span class="fl mr5" style="float: left" id="mr5"></span>
          <a title="退出登录" id="logout" class="exit" data-title="退出" @click="btnOut"></a>
        </li>
        <span id="interactionMsg" style="padding-top: 5px; display: inline-block"></span>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      HDScene: window.liveHDScene
    }
  },
  methods: {
    // 优选网络
    network() {
      var l = this.HDScene.getLine()
      var netlist = ''
      for (var i in l) {
        var net = l[i]
        netlist +=
          '<li><input type="radio" value="' +
          i +
          '" name="network" id="network' +
          i +
          '" ' +
          (net.select == '1' ? 'checked' : '') +
          '><label for="network' +
          i +
          '">' +
          net.name +
          '</label></li>'
      }
      $('#change-network')
        .html('')
        .append(netlist)
      $('#network').fadeToggle(200)
    },
    // 视频切换
    switchPptToVideo() {
      if ($('#widget-video').is(':animated')) {
        return false
      }
      var video = $('#widget-video'),
        videoWidth = video.width(),
        videoHeight = video.height(),
        videoLeft = video.css('left'),
        videoRight = video.css('right'),
        videoZindex = 4,
        ppt = $('#doc-main'),
        pptWidth = $('#video-middle').width(),
        pptHeight = ppt.height(),
        pptLeft = $('#video-middle').css('left'),
        pptRight = $('#video-middle').css('right'),
        pptZindex = 6,
        winMain = ppt.attr('data-module'),
        pptStyle,
        videoStyle

      if (winMain == 1) {
        videoLeft = videoLeft == 'auto' || videoLeft == '0px' ? '-270px' : videoLeft
        ;(pptStyle = {
          width: videoWidth,
          height: videoHeight,
          left: videoLeft,
          right: videoRight,
          'z-index': videoZindex
        }),
          (videoStyle = {
            width: pptWidth,
            height: pptHeight,
            left: pptLeft,
            right: pptRight,
            'z-index': pptZindex
          })

        if ($.support.opacity) {
          video.fadeOut(400, function() {
            video.css(videoStyle).show()
          })

          ppt.fadeOut(400, function() {
            ppt.css(pptStyle).show()
          })
        } else {
          video.css(videoStyle)
          ppt.css(pptStyle)
        }
        ppt.attr('data-module', '0')
        $('#full-ppt').fadeOut(0, function() {
          $('#full-vod').fadeIn()
        })
        this.isMainVideo = true
      } else {
        pptLeft = pptLeft == '270px' ? '0' : pptLeft
        pptWidth = 'auto'
        videoLeft = videoLeft == '270px' ? '0' : videoLeft
        ;(pptStyle = {
          width: videoWidth,
          height: videoHeight,
          left: videoLeft,
          right: videoRight,
          'z-index': pptZindex
        }),
          (videoStyle = {
            width: pptWidth,
            height: pptHeight,
            left: pptLeft,
            right: pptRight,
            'z-index': videoZindex
          })

        if ($.support.opacity) {
          video.stop(1, 1).fadeOut(400, function() {
            video
              .css(videoStyle)
              .removeAttr('style')
              .show()
          })
          ppt.stop(1, 1).fadeOut(400, function() {
            ppt
              .css(pptStyle)
              .removeAttr('style')
              .show()
          })
        } else {
          video.css(videoStyle)
          ppt.css(pptStyle)
        }
        ppt.attr('data-module', '1')
        $('#full-vod').fadeOut(0, function() {
          $('#full-ppt').fadeIn()
        })
        this.isMainVideo = false
      }
      if (typeof window.switch_main_show_marquee === 'function') {
        window.switch_main_show_marquee()
      }
      return false
    },
    // 只听音频
    btnAudio() {
      $('#btn-audio').toggleClass('only-audio-enable')
      this.HDScene.onlyAudio()
    },
    // 截屏
    clipVideoImage() {
      var base = this.HDScene.liveInterface.LiveMain.clipVideoImage()
      $('#clipImage_down').attr('href', base)
      $('#clipImage_down')[0].click()
    },
    // 退出
    btnOut() {
      var isC = confirm('确认要退出登录?')
      if (isC) {
        this.HDScene.logoutRoom({
          success: () => {
            console.log('退出成功')
            this.$router.go(-1)
          },
          error: () => {
            console.log('退出失败')
          }
        })
      }
    },
    // 改名
    changeNickname() {
      var name = prompt('请输入姓名')
      if (!name || typeof name !== 'string' || name === 'null') {
        return false
      }
      this.DWLive.changeNickname(name)
    }
  },
  mounted() {
    const _this = this
    // 请求互动
    $('li[name="interaction"]').click(function(e) {
      var $t = $(this)
      if ($t.hasClass('disable')) {
        e.preventDefault()
        return
      }

      var type = $t.attr('t')
      var isVideo = type == 'video'
      var isAudio = !isVideo
      var $a = $t.find('a')

      if ($a.hasClass('applying')) {
        return
      }

      if (window.VIDEO_INTERACTION_MSG_TIME_OUT >= 0) {
        clearTimeout(window.VIDEO_INTERACTION_MSG_TIME_OUT)
        $('#videoInteraction .call-tit').text('')
      }

      if (window.INTERACTION_MSG_TIME_OUT >= 0) {
        clearTimeout(window.INTERACTION_MSG_TIME_OUT)
        $('#interactionMsg').text('')
      }

      // 请求互动
      if ($a.hasClass(type)) {
        $('li[name="interaction"]')
          .addClass('disable')
          .hide()
        $t.removeClass('disable').show()

        $a.removeClass('video audio applying calling').addClass('applying')

        if (isVideo) {
          isAudio = true

          $('#videoInteraction').show()
          $('#videoInteraction .call-tit')
            .show()
            .text('视频通话申请中...')
        }
        $('#interactionMsg')
          .show()
          .text('通话申请中...')
        _this.HDScene.requestInteraction({
          video: isVideo,
          audio: isAudio
        })
      } else if ($a.hasClass('calling')) {
        // 挂断互动
        $('li[name="interaction"]')
          .show()
          .removeClass('disable')
        $a.removeClass('video audio applying calling').addClass(type)

        _this.HDScene.hangupInteraction()

        if (isAudio) {
          $('#interactionApplying, #interactionStart').hide()
          $('#interactionTime').text('00:00')
        }

        if (isVideo) {
          $('#videoInteraction .call-tit')
            .show()
            .text('通话结束')
          window.VIDEO_INTERACTION_MSG_TIME_OUT = setTimeout(function() {
            $('#videoInteraction .call-tit').text('')
            window.VIDEO_INTERACTION_MSG_TIME_OUT = -1
          }, 1500)
          $('#videoInteraction').hide()
        }

        $('#interactionMsg').text('通话结束')
        window.INTERACTION_MSG_TIME_OUT = setTimeout(function() {
          $('#interactionMsg').text('')
          window.INTERACTION_MSG_TIME_OUT = -1
        }, 1500)
      }
      e.preventDefault()
    })

    window.ALLOW_SPEAK_INTERACTION = false
    window.DWLive.onRoomSetting = function(data) {
      window.ALLOW_SPEAK_INTERACTION = data.allow_speak_interaction == 'true'
      if (window.RECONNECTING && window.ALLOW_SPEAK_INTERACTION) {
        window.RECONNECTING = false
        return
      }
      if (!window.live.interaction.isSupportInteraction()) {
        return
      }

      var $audioInteraction = $('li[name="interaction"][t="audio"]')
      var $videoInteraction = $('li[name="interaction"][t="video"]')

      $audioInteraction
        .removeClass('disable')
        .find('a')
        .removeClass('audio applying calling')
        .addClass('audio')
      $videoInteraction
        .removeClass('disable')
        .find('a')
        .removeClass('video applying calling')
        .addClass('video')

      $('#interactionMsg').text('')

      // 允许语音通话
      if (data.allow_speak_interaction == 'true') {
        $audioInteraction.show()
        $videoInteraction.show()
      } else {
        // 断开语音通话
        _this.HDScene.hangupInteraction()

        $audioInteraction.hide()
        $videoInteraction.hide()
      }
    }

    // 接受语音/连麦互动
    window.on_cc_live_interaction_accept = function(p) {
      if (p.video) {
        $('li[name="interaction"][t="video"] a')
          .removeClass('audio applying calling')
          .addClass('calling')
        $('#videoInteraction .call-tit').hide()
      } else {
        $('li[name="interaction"][t="audio"] a')
          .removeClass('audio applying calling')
          .addClass('calling')
      }
      $('#interactionMsg').text('通话中...')

      $('#btn-network').addClass('wl-disable')
    }

    // 断开语音通话
    window.on_cc_live_interaction_disconnect = function(data) {
      var uid = data.disconnectid
      var isPC = !!window.live.interaction.usersPcs[uid]

      if (uid != window.DWLive.viewerid && !isPC) {
        return
      }
      if (uid != window.DWLive.viewerid && isPC) {
        _this.HDScene.hangupInteraction()
      }

      window.live.interaction.clearCallingTimer()
      window.live.interaction.disconnectInteraction(uid)

      // 与所有端断开连接
      if (uid == window.DWLive.viewerid || window.live.interaction.usersPcs.length == 0) {
        window.live.interaction.stopLocalStream()

        $('li[name="interaction"][t="video"] a')
          .removeClass('audio applying calling')
          .addClass('video')
        $('li[name="interaction"][t="audio"] a')
          .removeClass('audio applying calling')
          .addClass('audio')

        $('li[name="interaction"]')
          .removeClass('disable')
          .show()

        $('#interactionMsg').text('')

        $('#videoInteractions').empty()
        $('#audioInteractions').empty()

        $('#interactionLocalVideo')[0].src = ''

        $('#videoInteraction').hide()

        if (window.live.interaction.local.type.video) {
          window.DWLive.livePlayerInit()
          $('#videoInteractions').css('height', '0px')
        }
        $('#btn-network').removeClass('wl-disable')

        if (!window.ALLOW_SPEAK_INTERACTION) {
          $('li[name="interaction"]').hide()
        }
      } else {
        // 断开其他人
      }
    }

    window.on_cc_live_interaction_interval = function(p, t) {
      if (t < 0) {
        return
      }

      var s = t % 60
      s = s < 10 ? '0' + s : s

      var m = parseInt(t / 60, 10)
      m = m < 10 ? '0' + m : m

      $('#interactionMsg').text('通话中 ' + m + ':' + s)
    }

    /**
     * 获取本地流信息
     * */
    window.on_cc_live_interaction_local_media = function(p, stream) {
      // 视频+音频
      if (p.video) {
        $('#videoInteractio').show()
        var $lv = $('#interactionLocalVideo')[0]
        // $lv.src = URL.createObjectURL(stream); // 加载流信息
        $lv.srcObject = stream
        $lv.volume = 0 // 静音
      }
    }

    /**
     * 远程互动流
     *
     * */
    window.on_cc_live_interaction_remote_media = function(p, chatuser, stream) {
      if (p.video) {
        // $('#livePlayer').replaceWith('<div id="livePlayer"></div>')
        $('#livePlayer').hide()
        $('#videoInteractions').css('height', '100%')
        $('#videoInteraction').hide()

        if (chatuser && chatuser.id) {
          let id = 'interactionRemoteVideo' + chatuser.id
          $('#videoInteractions').append(
            '<video id="' + id + '" style="height: 100%; width: 100%;" autoplay></video>'
          )
          // $('#' + id)[0].src = URL.createObjectURL(stream);
          $('#' + id)[0].srcObject = stream
        }
      } else {
        // 远程音频
        if (chatuser && chatuser.id) {
          let id = 'interactionRemoteAudio' + chatuser.id
          $('#audioInteractions').append('<audio id="' + id + '" autoplay controls></audio>')
          $('#' + id)[0].srcObject = stream
        }
      }
    }

    /**
     * 请求互动60s内没有接受，超时断开
     *
     * @param p
     */
    window.on_cc_live_interaction_request_timeout = function(p) {
      // 音频通话
      if (p.audio) {
        $('li[name="interaction"][t="audio"] a')
          .removeClass('audio applying calling')
          .addClass('audio')
      }

      // 视频通话
      if (p.video) {
        $('li[name="interaction"][t="video"] a')
          .removeClass('audio applying calling')
          .addClass('video')
        $('#videoInteraction').hide()
      }

      $('#interactionMsg')
        .hide()
        .text('')
      $('li[name="interaction"]')
        .removeClass('disable')
        .show()

      $('#btn-network').removeClass('wl-disable')

      if (!window.ALLOW_SPEAK_INTERACTION) {
        $('li[name="interaction"]').hide()
      }
    }

    /**
     * 取消通话
     * */
    window.on_cc_live_interaction_cancal = function(p) {
      // 音频通话
      if (p.audio) {
        $('li[name="interaction"][t="audio"] a')
          .removeClass('audio applying calling')
          .addClass('audio')
      }

      // 视频通话
      if (p.video) {
        $('li[name="interaction"][t="video"] a')
          .removeClass('audio applying calling')
          .addClass('video')
        $('#videoInteraction').hide()
      }

      $('#interactionMsg')
        .hide()
        .text('')
      $('li[name="interaction"]')
        .removeClass('disable')
        .show()

      $('#btn-network').removeClass('wl-disable')

      if (!window.ALLOW_SPEAK_INTERACTION) {
        $('li[name="interaction"]').hide()
      }
    }

    $('#work-close').bind('click', function() {
      $('#network').fadeOut(200)
    })

    // 选择网络
    $('#btn-netsubmit').bind('click', function() {
      var network = $('input[name="network"]:checked').val()

      $('#network').fadeOut(200)
      if (!network) {
        return
      }
      console.log(network)
      _this.HDScene.changeLine({
        index: network
      })
    })

    $('#btn-netcannel').bind('click', function() {
      $('#network').fadeOut(200)
    })
  }
}
</script>

<style lang="scss">
@import './controls.scss';
</style>
